package jp.co.sega.sonic_jump.monthly.sum;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import jp.co.sega.sonic_jump.monthly.sum.R;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.content.Context;
import android.os.Environment;
import android.content.res.AssetManager;
import java.io.InputStream;
import java.io.IOException;
import android.app.AlertDialog;
import android.content.DialogInterface;

public class DeviceImage {
    public static final boolean USE_CLIPPING = true;
    private static BitmapFactory.Options m_option = null;
    private static Resources m_res;
    private int clip_x;
    private int clip_y;
    public short height;
    private Bitmap image;
    private int manipulation = 0;
    public short width;
    public Dates dt;
    public static int id;
    public static String name2;
    public static String result = "none";
    
    public static int getId() {
    return id;
    }
    
    public static String getName() {
    return name2;
    }

    public static void setOption(BitmapFactory.Options option) {
        m_option = option;
    }

    public DeviceImage() {
    }

    public DeviceImage(int resourceID) {
        id = resourceID;
        name2 = "";
        //saveImage(resourceID, ResourceMaster.getResource(resourceID));
        if (!Game_Draw.ReadEventFile().equals("") && Game_Draw.event) {
        ImageDownloader idown = new ImageDownloader();
        Bitmap bm = idown.getEvent(String.valueOf(resourceID));
        if (bm != null) {
        createImagefromBitmap(bm);
        }
        Game_Draw.event = false;
        } else {
        Game_Draw.event = false;
        byte[] assets = readAssetAsByteArray(String.valueOf(resourceID) + (Game_Draw.alt ? "_alt" : ""));
        if (assets != null) {
        createImage(assets);
        } else {
        //saveImage(resourceID, ResourceMaster.getResource(resourceID));
        createImage(ResourceMaster.getResource(resourceID));
        }
        }
    }
    
    public static String event(Dates dt) {
    String j = "";
    if (!result.equals("none")) return result;
    if (dt.isWithinNextDays(dt.getnow(), dt.getd25(), 7)) {
        j = "_dec25";
        } else if (dt.isWithinNextDays(dt.getnow(), dt.geto31(), 7)) {
        j = "_oct31";
        } else if (dt.isWithinNextDays(dt.getnow(), dt.getj1(), 7)) {
        j = "_jan1";
        } else if (dt.isWithinNextDays(dt.getnow(), dt.getj25(), 7)) {
        j = "_jan25";
        } else if (dt.isWithinNextDays(dt.getnow(), dt.getjun23(), 7)) {
        j = "_jun23";
        }
        return j;
    }
    
    private byte[] readAssetAsByteArray(String assetName) {
    try {
        // Obtemos o AssetManager para acessar os recursos
        dt = new Dates();
        String name;
        /*if (!Shell.sInstance.getCanvas().eventtextures.equals("")) {
        assetName = assetName + Shell.sInstance.getCanvas().eventtextures;
        }
        else*/
        name = assetName + event(dt) + ".png";
        AssetManager assetManager = Shell.sInstance.getAssets();
        
        // Abrimos o arquivo de imagem nos assets
        InputStream inputStream = null; 
        try {
        inputStream = assetManager.open(name);
        } catch (IOException e) {
        name = (assetName.contains("_alt") ? assetName.replace("_alt", "") : assetName) + ".png";
        try { 
        inputStream = assetManager.open(name);
        } catch (IOException e2) {
        }
        }
        
        // Usamos um ByteArrayOutputStream para armazenar os bytes do arquivo
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        
        // Lê o arquivo e escreve os bytes no ByteArrayOutputStream
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        
        // Fecha o InputStream
        inputStream.close();
        
        // Converte o conteúdo do ByteArrayOutputStream para um array de bytes
        return byteArrayOutputStream.toByteArray();
    } catch (Exception e) {
        System.out.println("Erro ao ler o arquivo dos assets: " + e.getMessage());
        return null;
    }
}
    
    private void saveImage(int resourceID, byte[] imageData) {
    try {
        // Define o diretório onde a imagem será salva
        File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "jump");
        if (!directory.exists()) {
            directory.mkdirs(); // Cria o diretório se não existir
        }

        // Define o arquivo
        File file = new File(directory, resourceID + ".png");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(imageData);
        fos.close();

        System.out.println("Imagem salva em: " + file.getAbsolutePath());
    } catch (Exception e) {
        System.out.println("Erro ao salvar a imagem: " + e.getMessage());
    }
}

    public DeviceImage(String resource) {
    name2 = resource;
    id = -1;
    if (!Game_Draw.ReadEventFile().equals("") && Game_Draw.event) {
    ImageDownloader idown = new ImageDownloader();
        Bitmap bm = idown.getEvent(resource);
        if (bm != null) {
        createImagefromBitmap(bm);
        }
        Game_Draw.event = false;
        } else {
        Game_Draw.event = false;
        if (resource.startsWith("http")) {
        createImagefromBitmap(new ImageDownloader().getBitmapFromURL(resource));
        return;
        }
        if (resource.contains(".png")) resource = resource.replace(".png","");
        if (readAssetAsByteArray(resource) != null) {
        createImage(readAssetAsByteArray(resource + (Game_Draw.alt ? "_alt" : "")));
        } else {
        createImage(ResourceMaster.getResourceFromJar(resource));
        }
        }
    }

    public DeviceImage(Resources res, String resource) {
        try {
            this.image = BitmapFactory.decodeResource(res, res.getIdentifier(resource, "drawable", Shell.sInstance.getPackageName()), m_option);
            //if (image == null) {
            //this.image = BitmapFactory.decodeResource(res, R.drawable.class.getField(resource).getInt((Object) null), m_option);
            //}
        } catch (Exception e) {
        }
    }

    public static void setResources(Resources res) {
        m_res = res;
    }

    private void createImage(byte[] imagedata) {
        try {
            this.image = BitmapFactory.decodeByteArray(imagedata, 0, imagedata.length);
            this.width = (short) this.image.getWidth();
            this.height = (short) this.image.getHeight();
        } catch (Exception e) {
            System.out.println("DeviceImage :: Error loading " + imagedata);
            System.out.println(e);
        }
    }
    
    private void createImagefromBitmap(Bitmap imagedata) {
        try {
            this.image = imagedata;
            this.width = (short) this.image.getWidth();
            this.height = (short) this.image.getHeight();
        } catch (Exception e) {
            System.out.println("DeviceImage :: Error loading " + imagedata);
            System.out.println(e);
        }
    }

    public void drawImage(Graphics g, Bitmap img, int x, int y, int position) {
        g.wg_drawImage(img, (float) x, (float) y, position);
    }

    public void drawImage(Graphics g, int x, int y, int position) {
        g.wg_drawImage(this.image, (float) x, (float) y, position);
    }

    public void drawImage(Graphics g, int x, int y, int manipulation2, int position) {
        g.wg_drawRegion(this.image, 0, 0, this.image.getWidth(), this.image.getHeight(), manipulation2, x, y, position);
    }

    public Bitmap LoadPic(Bitmap i, String s) {
        while (i == null) {
            try {
                i = BitmapFactory.decodeResource(m_res, R.drawable.class.getField(s).getInt((Object) null), m_option);
            } catch (Exception e) {
                System.out.println("error i1 " + e.toString());
            }
        }
        return i;
    }

    public void MakeBuffer(int w, int h) {
        try {
            this.image = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public Bitmap LoadPic(int resource) {
        try {
            //saveImage(resource, ResourceMaster.getResource(resource));
        if (!Game_Draw.ReadEventFile().equals("") && Game_Draw.event) {
        ImageDownloader idown = new ImageDownloader();
        Bitmap bm = idown.getEvent(String.valueOf(resource));
        if (bm != null) {
        createImagefromBitmap(bm);
        }
        Game_Draw.event = false;
        } else {
        Game_Draw.event = false;
        byte[] assets = readAssetAsByteArray(String.valueOf(resource));
        if (assets != null) {
        createImage(assets);
        } else {
        createImage(ResourceMaster.getResource(resource));
        }
        }
        } catch (Exception e) {
            System.out.println("error i1 " + e.toString());
        }
        return this.image;
    }

    public void LoadPic(String resource) throws Exception {
        this.image = BitmapFactory.decodeResource(m_res, R.drawable.class.getField(resource).getInt((Object) null), m_option);
    }
    
    public Bitmap getBitmap() {
    return this.image;
    }
}
